<script setup lang="ts" name="GroupForm">
import { reactive, ref, getCurrentInstance } from 'vue'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { addGroupApi, getGroupTreeApi, updateGroupApi } from '@/addon/htscrm/api'
import { cloneDeep } from 'lodash-es'
import { t } from '@/lang'

const instance = getCurrentInstance() as any
const { $convert } = instance.appContext.config.globalProperties

const defaultFormData: IGroupItem = {
    id: 0,
    name: '',
    parent_id: 0,
    is_show: 1
}
/** 表单实例 */
const formRef = ref<FormInstance>()
/** 表单数据 */
const formData = ref<IGroupItem>({ ...defaultFormData })

// 表单规则
const formRules = reactive<FormRules>({
    name: [{ required: true, message: t('group.form.name.placeholder'), trigger: 'blur' }]
})

const groupList = ref<IGroupItem[]>([])

/**
 * @description 初始化
 */
function init (row?: IGroupItem, isEdit = false) {
    formRef.value?.resetFields()
    if (isEdit && row) {
        formData.value = { ...row }
    } else {
        formData.value = { ...defaultFormData, parent_id: row?.id || 0 }
    }

    getGroup()
}

/**
 * @description 获取分组列表
 */
async function getGroup () {
    const res = await getGroupTreeApi()
    groupList.value = res.data
}

/**
 * @description 提交保存
 */
function submit () {
    return new Promise((resolve, reject) => {
        formRef.value?.validate(async (valid) => {
            if (valid) {
                const params = cloneDeep(formData.value)

                // 表单校验
                params.id
                    ? await updateGroupApi(params)
                    : await addGroupApi(params)
                ElMessage.success(t('save.success'))
                resolve(true)
            } else {
                reject(new Error(t('form.validateError')))
            }
        })
    })
}

defineExpose({
    init,
    submit
})
</script>

<template>
  <el-form class="f-form" ref="formRef" label-width="100px" :model="formData" :rules="formRules">
    <el-form-item :label="t('group.form.parent')">
      <el-cascader
        v-model="formData.parent_id"
        :placeholder="t('group.form.parent.placeholder')"
        clearable
        :options="groupList"
        :props="{ checkStrictly: true, emitPath:false, multiple: false, children: 'child', value:'id',label: 'name' }"
      />
    </el-form-item>
    <el-form-item :label="t('group.form.name')" prop="name">
      <el-input v-model="formData.name" :placeholder="t('group.form.name.placeholder')" />
    </el-form-item>
     <el-form-item label="小程序ID">
      <el-input v-model="formData.miniapp_id" placeholder="请输入小程序ID" />
    </el-form-item>
    <el-form-item :label="t('group.form.is_show')" prop="is_show">
      <el-radio-group v-model="formData.is_show">
        <el-radio-button :label="t('show1')" :value="$convert(1, formData.is_show)" />
        <el-radio-button :label="t('show0')" :value="$convert(0, formData.is_show)" />
      </el-radio-group>
    </el-form-item>
  </el-form>
</template>
